package cn.geminis.lowcode.compiler;

import cn.geminis.lowcode.LcException;
import cn.geminis.lowcode.utils.Utils;

/**
 * @author puddi
 */
public class LcModule {

    private LcModule() {
    }

    /**
     * Useful from jdk9 and up; required from jdk16 and up. This code is supposed to gracefully do nothing on jdk8 and below, as this operation isn't needed there.
     */
    public static void addOpens() {
        ModuleLayer.boot().findModule("jdk.compiler")
                .ifPresent(jdkCompilerModule -> {
                    var allPkgs = new String[]{
                            "com.sun.tools.javac.code",
                            "com.sun.tools.javac.comp",
                            "com.sun.tools.javac.file",
                            "com.sun.tools.javac.main",
                            "com.sun.tools.javac.model",
                            "com.sun.tools.javac.parser",
                            "com.sun.tools.javac.processing",
                            "com.sun.tools.javac.tree",
                            "com.sun.tools.javac.util",
                            "com.sun.tools.javac.jvm",
                    };
                    try {
                        var implAddOpensMethod = jdkCompilerModule.getClass().getDeclaredMethod("implAddOpens", String.class);
                        implAddOpensMethod.setAccessible(true);
                        for (String pkg : allPkgs) {
                            implAddOpensMethod.invoke(jdkCompilerModule, pkg);
                        }
                        Utils.noteMessage("jdk.compiler module opened");
                    } catch (Exception e) {
                        throw new LcException("开放JDK内部方法异常", e);
                    }
                });
    }
}
